package org.cyrano.draw;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author Demián Gutierrez
 */
public class CustomDrawView extends View {

  private static final int RADIUS = 100;
  private static final int RECMED = 30;

  // --------------------------------------------------------------------------------

  private boolean init = true;

  private int cx;
  private int cy;

  private float percent = 0.5f;

  // --------------------------------------------------------------------------------

  public CustomDrawView(Context context) {
    super(context);
  }

  // --------------------------------------------------------------------------------

  private void init() {
    cx = Hwh.getW(this) / 2;
    cy = Hwh.getH(this) / 2;

    init = false;
  }

  // --------------------------------------------------------------------------------

  protected void onDraw(Canvas canvas) {
    if (init) {
      init();
    }

    Paint paint = new Paint();
    paint.setColor(Color.YELLOW);

    int w = Hwh.getW(this) / 2;
    int h = Hwh.getH(this) / 2;

    canvas.drawRect(new RectF( //
        w - RECMED, h - RECMED, w + RECMED, h + RECMED), paint);

    paint.setColor(Color.GREEN);
    paint.setAlpha(200);

    canvas.drawCircle(cx, cy, (float) (RADIUS * percent), paint);
  }

  // --------------------------------------------------------------------------------

  public void handleKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
      if (percent >= 0.25) {
        percent -= 0.05;
        invalidate();
      }

      return;
    }

    if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
      if (percent <= 1) {
        percent += 0.05;
        invalidate();
      }

      return;
    }
  }

  // --------------------------------------------------------------------------------

  public boolean onTouchEvent(MotionEvent event) {
    cx = (int) event.getX();
    cy = (int) event.getY();

    if (cy < 0) {
      cy = 0;
    }

    invalidate();

    return true;
  }
}
